var groupmap = {}, friendmap = {};

var COMMAND = {
		LOGIN : 0x1010,
		LOGIN_SUCCESS : 0x1110,
		LOGIN_FAIL : 0x1111,
		LOGOUT : 0x1020,
		MESSAGE2C : 0x2120,
		MESSAGE2C_SUCCESS : 0x2020,
		MESSAGE2C_FAIL : 0x2021,
		CMD_QUIT : 0x4110,
		LOCATION : 0x4020,
		HEARTBEAT : 0x8010
};
var IMG = {
		GROUP : URL.RES + "/img/icon_group.png",
		SERVICE : URL.RES + "/img/icon_service.jpg",
		CLIENT :　URL.RES + "/img/icon_client.jpg"
};

/*****************************************
 WebSocket兼容方案（AS3）   2013-08-20
 作者：次碳酸钴（admin@web-tinker.com）
 *****************************************/
var FlashSocket = function(url){
	var SRC = basePath + "/js/elinkim/WebSocket.swf";
	var id = Math.random()*1E9|0,events={},s,i;
	//事件关联
	s=["open","message","close","error"];
	for(i=0;i<s.length;i++)(function(o,n){
		var s=events[n]=[];
		window[n+id]=function(e){
			if(typeof o["on"+n]==="function")o["on"+n](e);
			for(var i=0;i<s.length;i++)s[i](e);
		};
	})(this,s[i]);
	//绑定事件操作函数
	this.addEventListener=function(e,f){
		events[e].push(f);
	},this.removeEventListener=function(e,f){
		for(var i=0,s=events[e];i<s.length;i++)
			if(s[i]===f)s.splice(i,1),i=s.length;
	};
	//绑定AS接口方法
	this.send=function(e){
		window["WebSocket"+id].send(e);
	},this.close=function(){
		window["WebSocket"+id].close();
	};
	//解析构造参数，加载SWF
	var o=url.match(/\/\/([\w.]+)(?::(\d+))?(.*$)/);
	o=[
		"id="+id,"port="+(o[2]||80),
		"host="+o[1],"path="+(o[3]||"/")
	].join("&");
	var data=[
		'<object width="0" height="0" ',
		'type="application/x-shockwave-flash" ',
		'id="WebSocket'+id+'" data="'+SRC+'">',
		'<param name="Movie" value="'+SRC+'" />',
		'<param name="FlashVars" value="'+o+'" />',
		'</object>'
	].join("");
	document.body
		?document.body.insertAdjacentHTML("beforeend",data)
		:document.write(data);
};

$(function() {
	loginMsg();
});

/**
 * 获取好友和群组列表
 * 连接socket接收消息
 */
function loginMsg() {
	var loginfo, groupinfo;
	$.getJSON(URL.LOGINFO, function(data) {
        if(data.status !== 10001) {
            return;
        }
        loginfo = data.data;

        $.getJSON(URL.EL_SERV + "/customer/getCustomerChat.do?", function (data) {
            if(data.status !== 10001) {
                alert(data.msg);
                return;
            }
            var list=[];
            data = data.data;
            for(var i=0; i<data.length; i++) {
                var group = {
                    "groupname": data[i].chatName
                    ,"id": data[i].chatId
                    ,"avatar": data.img || IMG.GROUP
                };
                list.push(group);
                groupmap[group.id] = group;
            }
            groupinfo = list;
            initim(loginfo, groupinfo);
            connect(loginfo);
        });
	});
}

/**
 * 初始化im组件
 * @param info
 * @param group
 */
function initim(info, group) {
	console.log("init im");
	layui.use('layim', function(layim) {
		// 基础配置
		layim.config({
			// 初始化接口
			init : {
				mine : {
					"username" : info.nickName,
					"id" : info.mobile,
					"statue" : "online",
					"remark" : info.userName,
					"avatar" : info.headImage ? URL.IMG + info.headImage : IMG.SERVICE
				}
				,group : group
			}
			// 查看群员接口
			,members : {
				url : URL.EL_SERV + '/chat/getChatRoomMemberList.do?',
				data : {}
			}
			// 上传图片接口
			,uploadImage : {
				url : basePath + '/message/getUploadFilePath.do?compress=0'
			}
			// 上传文件接口
			,uploadFile : {
				url : basePath + '/message/getUploadFilePath2.do'
			}
            ,title : "8718客服"
			,isfriend : false
			,initSkin : '3.jpg' // 1-5 设置初始背景
			,notice : true // 是否开启桌面消息提醒，默认false
            ,logout : basePath + "/login/logout.do"
		});

		// 监听发送消息
		layim.on('sendMessage', function(data) {
			// console.log(data);
			var param = {};
			var url = basePath + "/chat/sendChatMessage.do?";
			param.userFromId = data.mine.id;

			if(data.to.type === "group") {
				param.chatId = data.to.id;
				param.dataType = "groupchat";
			}
			else if(data.to.type === "friend") {
				param.userToId = data.to.id;
				param.dataType = "chat";
			}
			var content = data.mine.content;
			var imgre = /^img\[([^\s]+?)\]$/;
			var filere = /^file\([\s\S]+?\)\[[\s\S]*?\]$/;
			if(imgre.test(content)) {
				url = URL.EL_SERV + "/message/sendAllFileMessageNotUpload.do?";
				param.message = content.replace(/(^img\[)|(\]$)/g, '');
				param.messageType = "image";
			}
			else if(filere.test(content)) {
				url = URL.EL_SERV + "/message/sendAllFileMessageNotUpload.do";
				param.message = (content.match(/file\(([\s\S]+?)\)\[/)||[])[1];
				param.fileName = (content.match(/\)\[([\s\S]*?)\]/)||[])[1];
				param.messageType = "file";
			}
			else {
				param.messageType = "text";
				param.message = content;
			}

			$.getJSON(url, param, function(res) {
				if(res.status !== 10001) {
					alert("send failed");
				}
			});
		});

		// 监听查看群员
		layim.on('members', function(data) {
			// console.log(data);
		});

		// 监听聊天窗口的切换
		layim.on('chatChange', function(res) {
			var data = res.data;
			var elem;
	    	if(data.type === "friend") {
	    		elem = friendmap[data.id];
	    	}
	    	else if(data.type === "group") {
	    		elem = groupmap[data.id];
	    	}
	    	if(elem) {
	    		delete elem["unread"];
	    	}
	    	
			var chatli = $("#layim-" + data.type + data.id);
			if(chatli) {
				chatli.find(".layui-badge").remove();
			}
		    var historyli = $("#layim-history" + data.id);
		    if(historyli) {
				historyli.find(".layui-badge").remove();
			}
		    var listli = $(".layim-chatlist-" + data.type + data.id);
		    if(listli) {
				listli.find(".layui-badge").remove();
			}
		});
	});
}

/**
 * 连接socket，并做用户验证
 * @param loginfo
 */
function connect(loginfo) {
	var socket;
	if(window.WebSocket) {
		socket = new WebSocket(URL.WSS_SERV || URL.WS_SERV);
	}
	else {
		socket = new FlashSocket(URL.WS_SERV);
	}

	// 打开Socket 
	socket.onopen = function() {
		// 发送一个初始化消息
		var obj = {
				command : COMMAND.LOGIN,
				userAgent : "PC; 8718platform-v1",
				id : loginfo.mobile,
				token : loginfo.token
		};
		socket.send(JSON.stringify(obj));
	};
	
	// 监听消息
	socket.onmessage = function(event) {
//		console.log('Client received a message', event);
		var msg = $.parseJSON(event.data);
		switch (msg.command) {
		case COMMAND.LOGIN_SUCCESS:
			break;
		case COMMAND.LOGIN_FAIL:
			alert("login failed");
			break;
		case COMMAND.MESSAGE2C:
			var resp = {
					command : COMMAND.MESSAGE2C_SUCCESS,
					mid : msg.msgId
			};
			socket.send(JSON.stringify(resp));
            var obj = formatMsg(msg);
			if(obj !== null) {
				layui.layim.getMessage(obj);
			}
			break;
        case COMMAND.CMD_QUIT:
            layer.open({
                type: 1
                ,content: '<div style="padding: 20px 40px;">' + '该账号已在其他设备登陆！' + '</div>'
                ,btn: '确定'
                ,btnAlign: 'c'
                ,yes: function(){
                    window.location.href=layui.layim.cache().base.logout;
                }
            });
            break;
		default:
			break;
		}
	};

	// 监听Socket的关闭
	socket.onclose = function(event) {
		console.log('Client notified socket has closed', event);
	};
	
	socket.onerror = function(event) {
		console.log('an error has happened', event);
	};

	// 关闭Socket.... 
	//socket.close() 
	
}

/**
 * 聊天类型转换
 * @param data
 * @returns {*}
 */
function formatType(data) {
	switch (data) {
	case "chat":
		return "friend";
	case "groupchat":
		return "group";
	default:
		return data;
	}
}

/**
 * 解析消息内容
 * @param data
 * @returns {*}
 */
function formatMsg(data) {
	var obj = {};
	obj.type = formatType(data.dataType);
	var cache = layui.layim.cache();
	if(data.fromId === cache.mine.id) {
		if(obj.type === "friend") {
			obj.username = cache.mine.username;
			obj.avatar = cache.mine.avatar;
			obj.id = data.toId;
			obj.mine = true;
		}
		else if(obj.type === "group") {
			obj.id = data.chatId;			
			obj.username = cache.mine.username;
			obj.avatar = cache.mine.avatar;
			obj.mine = true;
		}
	}
	else {
		if(obj.type === "friend") {
			obj.id = data.fromId;
			if(friendmap[obj.id] === undefined) {
				return null;
			}
			else {
				obj.username = friendmap[obj.id].username;
				obj.avatar = friendmap[obj.id].avatar;
			}
		}
		else if(obj.type === "group") {
			obj.id = data.chatId;
			obj.fromid = data.fromId;
			obj.timestamp = Number(data.createdAt);
			if(groupmap[obj.id] === undefined) {
				newGroupMessage(obj.id, function() {
					var obj = formatMsg(data);
					if(obj !== null)
						layui.layim.getMessage(obj);
				});
				return null;
			}
			if(friendmap[obj.fromid] === undefined) {
				newFriendMessage(obj.fromid, function() {
					var obj = formatMsg(data);
					if(obj)
						layui.layim.getMessage(obj);
				});
				return null;
			}

			var friend = friendmap[obj.fromid];
			// var uname = friend.id.indexOf("8718") === 0 ? friend.username :
             //    friend.username + '[' + friend.sign + ']';
			obj.username = friendmap[obj.fromid].username;
			obj.avatar = friendmap[obj.fromid].avatar;
		}
	}
	
	var re = /<EasyLink\s+Type\s*=\s*"([^"]+)"\s+Value\s*=\s*"([\s\S]+)"\s+Title\s*=\s*"([^"]+)"\s*\/>/;
	var r = re.exec(data.msgBody);
	if(r[1] === "Text") {
		obj.content = r[2];
		if(obj.type === "group") {	//	群聊中@做转义
			var at = [];
			while (at = obj.content.match(/@(\d+) /)) {
				if(!friendmap[at[1]]) {
					newFriendMessage(at[1], function() {
						var obj = formatMsg(data);
						if(obj)
							layui.layim.getMessage(obj);
					});
					return null;
				}
				obj.content = obj.content.replace(at[0], "@["+at[1]+"|"+friendmap[at[1]].username+"]");
			}
		}
	}
	else if(r[1] === "Image") {
		obj.content = "img[" + r[2] + "]";
	}
	else if(r[1] === "File") {
		var v = $.parseJSON(r[2]);
		obj.content = 'file(' + v.path + ')[' + v.fileName + ']';
	}
	else if(r[1] === "Announcement") {
		var are = /^code=(\d+)-newChatName=(.*)-text=(.*)-targetId=(\d*)$/;
		var values = are.exec(r[2]);
		obj.system = true;
		obj.content = values[3];
		if(values[1] === "103" && values[4] === cache.mine.id) {	//	被踢
			$("#layim-group" + obj.id).remove();
		}
		else if(groupmap[obj.id].groupname !== values[2]) {
			groupmap[obj.id].groupname = values[2];
			var content = $("#layim-group" + obj.id);
			if(content) {
				content.find("span").eq(0).html(values[2]);
				for(var i=0; i<cache.group.length; i++) {
					if(cache.group[i].id === obj.id) {
						cache.group[i].groupname = values[2];
						break;
					}
				}
			}
			content = $("#layim-history" + obj.id);
			if(content) {
				content.find("span").eq(0).html(values[2]);
				cache.history["group"+obj.id].groupname = values[2];
				//	修改缓存
				var local = layui.data('layim-'+cache.mine.id) || {};
				local.history["group"+obj.id].groupname = values[2];
				layui.data('layim-'+cache.mine.id, {key: "history", value: local.history});
			}
			content = $(".layim-chatlist-group" + obj.id);
			if(content) {
				var idx = content.index();
				content.find("span").eq(0).html(values[2]);
				$(".layim-chat-username").eq(idx).html(values[2]);
			}
		}
	}
	else {
		obj.system = true;
		obj.content = "收到一条不支持的消息，请到手机端查看";
	}
	return obj;
}

/**
 * 收到新的组群发来的消息
 */
function newGroupMessage(id, callback) {
	if(groupmap[id] === undefined) {
		$.getJSON(basePath+'/chat/getGroupChat2.do?', {chatIds : id}, function(data) {
			if(data.status === 10001 && data.data.length > 0) {
				data = data.data[0];
				var group = {
						type : 'group'
						,groupname: data.chatName
				        ,id: id
				        ,avatar: data.img || IMG.GROUP
				};
				if(groupmap[id] === undefined) {
					groupmap[id] = group;
					layui.layim.addList(group);
				}
			}
			callback();
		});
	}
	else {
		callback();
	}
}

/**
 * 收到新的朋友发来的消息
 */
function newFriendMessage(id, callback) {
	if(friendmap[id] === undefined) {
		$.getJSON(basePath+'/customer/getUserInfo.do?', {mobile : id}, function(data) {
			if(data.status === 10001) {
				data = data.data;
				var friend = {
						"username": data.nickName + "[" + data.userName + "]"
				        ,"id": data.mobile
				        ,"groupid": 2
				        ,"avatar": data.headImage ? (URL.IMG + data.headImage) : (data.mobile.indexOf('8718') === 0 ? IMG.SERVICE : IMG.CLIENT)
				        ,"sign": data.userName +"|"+ data.userCompany
				        ,"type": "friend"
				};
				if(friendmap[id] === undefined) {
					friendmap[id] = friend;
				}
				callback();
			}
		});
	}
	else {
		callback();
	}
}

/**
 * 更新会话角标
 * @param data
 */
function updateBadge(data) {
	var elem;
	if(data.type === "friend") {
		elem = friendmap[data.id];
	}
	else if(data.type === "group") {
		elem = groupmap[data.id];
	}
	if(elem) {
		var chatli = $("#layim-" + data.type + data.id);
	    var historyli = $("#layim-history" + data.id);
	    var listli = $(".layim-chatlist-" + data.type + data.id);
	    if(elem.unread) {
	    	elem.unread += 1;
	    	if(chatli) {
	    		chatli.find(".layui-badge").html(String(elem.unread));
	    	}
	    	if(historyli) {
	    		historyli.find(".layui-badge").html(String(elem.unread));
	    	}
	    	if(listli) {
	    		listli.find(".layui-badge").html(String(elem.unread));
	    	}
	    }
	    else {
	    	elem.unread = 1;
	    	if(chatli) {
	    		chatli.append('<span class="layui-badge" style="position: absolute; right: 5px; top: 13px;">1</span>');
	    	}
	    	if(historyli) {
	    		historyli.append('<span class="layui-badge" style="position: absolute; right: 5px; top: 13px;">1</span>');
	    	}
	    	if(listli) {
	    		listli.append('<span class="layui-badge" style="position: absolute; right: 5px; top: 13px; width:auto; padding: 3px 6px;">1</span>');
	    	}
	    }
	}
}

function showUserInfo(mobile) {
	if(mobile)
		$.getJSON(basePath + "/customer/getUserInfo.do?", {
			mobile : mobile
		}, function (data) {
			if(data.status === 10001) {
				data = data.data;
				var table = ['<table class="layui-table">',
					'<colgroup><col width="100"><col width="150"></colgroup>',
					'<tbody>',
					'<tr><td>姓名</td><td>', data.userName, '</td></tr>',
					'<tr><td>昵称</td><td>', data.nickName, '</td></tr>',
					'<tr><td>手机</td><td>', data.mobile, '</td></tr>',
					'<tr><td>公司</td><td>', data.userCompany, '</td></tr>',
					'</tbody>',
					'</table>'].join('');
				layer.open({
					type : 0,
					title : "客户信息",
					content : table
				});
			}
		});
}

function showImage(url) {
	if(url) {
        layer.open({
            type : 0,
            title : url,
            area : ['600px', '480px'],
            content : '<div style="overflow: auto">' + '<img src="' + url + '"></div>'
        });
	}
}